package dev.kaayf.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CoverUploader {
    private static final String TAG = "CoverUploader";
    public static final int PICK_IMAGE_REQUEST = 13;
    private Activity activity;
    private String currentPhotoPath;

    public CoverUploader(Activity activity) {
        this.activity = activity;
    }

    public void selectImage() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        activity.startActivityForResult(Intent.createChooser(intent, "Select a cover"), PICK_IMAGE_REQUEST);
    }

    public String saveImageToInternalStorage(Uri imageUri) {
        try {

            InputStream inputStream = activity.getContentResolver().openInputStream(imageUri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();


            File storageDir = new File(activity.getFilesDir(), "images");
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }


            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String fileName = "KAAYF_NOTE_" + timeStamp + ".jpg";
            File imageFile = new File(storageDir, fileName);


            FileOutputStream outputStream = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
            outputStream.close();

            return imageFile.getAbsolutePath();

        } catch (Exception e) {
            Log.e(TAG, "Image saving failed " + e.getMessage());
            return null;
        }
    }


}